#!/usr/bin/env python3
"""
简化爬取启动器 - 第1.5阶段增强版
提供简单直观的爬取界面：城市选择 → 品类发现 → 品类选择 → 开始爬取
"""

import sys
import logging
import time
from pathlib import Path
from typing import List, Dict, Any

# 添加项目路径
sys.path.append(str(Path(__file__).parent))

from core.crawler_core import CrawlerCore
from utils.logger import setup_logger

# 设置日志
logger = setup_logger('simple_crawl', 'logs/simple_crawl.log')

class SimpleCrawlLauncher:
    """简化爬取启动器"""
    
    def __init__(self):
        """初始化启动器"""
        self.crawler = None
        self.supported_cities = [
            '深圳', '苏州', '杭州', '长沙',
            '上海', '广州', '成都', '重庆',  '武汉'
        ]
        
    def print_welcome_banner(self):
        """打印欢迎横幅"""
        banner = """
╔══════════════════════════════════════════════════════════════════════╗
║                    🚀 简化智能爬取启动器                            ║
║                                                                      ║
║  特性：                                                              ║
║    • 🏙️  城市选择：支持15个主要城市                                ║
║    • 🔍 动态品类发现：自动发现城市可用品类                          ║
║    • 🎯 灵活品类选择：从发现的品类中选择1-2个                       ║
║    • 📊 明确数据预期：每次600-700条数据                             ║
║    • 🤖 智能账号管理：自动轮换，网络隔离                            ║
║                                                                      ║
║  目标：简单易用，一键启动，智能爬取                                  ║
╚══════════════════════════════════════════════════════════════════════╝
        """
        print(banner)
    
    def initialize_system(self) -> bool:
        """初始化系统"""
        print("🔧 正在初始化智能爬取系统...")
        
        try:
            self.crawler = CrawlerCore()
            
            # 检查第1.5阶段功能
            if not self.crawler.phase_1_5_enabled:
                print("❌ 第1.5阶段功能未启用，请检查系统配置")
                return False
            
            print("✅ 系统初始化成功")
            return True
            
        except Exception as e:
            print(f"❌ 系统初始化失败: {e}")
            return False
    
    def show_system_status(self):
        """显示系统状态"""
        print("\n📊 系统状态检查:")
        
        try:
            # 获取第1.5阶段状态
            phase_status = self.crawler.get_phase_1_5_status()
            
            if phase_status['enabled']:
                print("  ✅ 第1.5阶段功能: 已启用")
                
                # 账号池状态
                account_status = phase_status['account_manager']['pool_status']
                company_available = account_status['company_pool']['available']
                home_available = account_status['home_pool']['available']
                
                print(f"  📱 账号池状态:")
                print(f"    公司网络: {company_available}/{account_status['company_pool']['total']} 可用")
                print(f"    家庭网络: {home_available}/{account_status['home_pool']['total']} 可用")
                
                # 调度器状态
                scheduler_status = phase_status['scheduler']['status']
                current_network = scheduler_status['current_network']
                should_crawl = scheduler_status['should_crawl']
                
                print(f"  🌐 网络环境: {current_network}")
                print(f"  ⏰ 当前时段: {scheduler_status['current_time_slot']}")
                print(f"  🚀 适合爬取: {'是' if should_crawl else '否'}")
                
                if not should_crawl:
                    next_optimal = scheduler_status.get('next_optimal_time')
                    if next_optimal:
                        print(f"    💡 建议时间: {next_optimal}")
                
                return True
            else:
                print("  ❌ 第1.5阶段功能: 未启用")
                return False
                
        except Exception as e:
            print(f"  ❌ 状态检查失败: {e}")
            return False
    
    def select_city(self) -> str:
        """城市选择"""
        print("\n🏙️ 步骤1: 选择目标城市")
        print("支持的城市:")
        
        # 分组显示城市
        for i, city in enumerate(self.supported_cities, 1):
            print(f"  {i:2d}. {city}", end="")
            if i % 5 == 0:  # 每5个城市换行
                print()
        
        if len(self.supported_cities) % 5 != 0:
            print()
        
        while True:
            try:
                choice = input(f"\n请选择城市 (1-{len(self.supported_cities)}) 或直接输入城市名: ").strip()
                
                # 尝试解析为数字
                if choice.isdigit():
                    index = int(choice) - 1
                    if 0 <= index < len(self.supported_cities):
                        selected_city = self.supported_cities[index]
                        print(f"✅ 已选择城市: {selected_city}")
                        return selected_city
                    else:
                        print(f"❌ 请输入 1-{len(self.supported_cities)} 之间的数字")
                        continue
                
                # 尝试直接匹配城市名
                if choice in self.supported_cities:
                    print(f"✅ 已选择城市: {choice}")
                    return choice
                
                print(f"❌ 不支持的城市: {choice}")
                print(f"💡 支持的城市: {', '.join(self.supported_cities)}")
                
            except KeyboardInterrupt:
                print("\n👋 用户取消操作")
                return None
            except Exception as e:
                print(f"❌ 输入错误: {e}")
    
    def discover_and_select_categories(self, city_name: str) -> List[str]:
        """品类发现和选择"""
        print(f"\n🔍 步骤2: 发现 {city_name} 的可用品类")
        print("正在动态发现品类，请稍候...")
        
        try:
            # 发现品类
            available_categories = self.crawler.discover_city_categories(city_name)
            
            if not available_categories:
                print(f"❌ 无法发现 {city_name} 的品类，请检查网络连接")
                return []
            
            print(f"✅ 发现 {len(available_categories)} 个可用品类:")
            
            # 显示品类列表
            for i, category in enumerate(available_categories, 1):
                source_info = f"({category.get('source', 'unknown')})" if 'source' in category else ""
                print(f"  {i:2d}. {category['name']} {source_info}")
            
            # 品类选择
            print(f"\n🎯 步骤3: 选择要爬取的品类")
            print("💡 建议选择1-2个品类，预期每个品类300-350条数据")
            print("💡 输入格式: 单个数字(如: 1) 或多个数字用逗号分隔(如: 1,3)")
            
            while True:
                try:
                    choice = input("请选择品类编号: ").strip()
                    
                    if not choice:
                        print("❌ 请输入品类编号")
                        continue
                    
                    # 解析选择
                    selected_indices = []
                    for part in choice.split(','):
                        part = part.strip()
                        if part.isdigit():
                            index = int(part) - 1
                            if 0 <= index < len(available_categories):
                                selected_indices.append(index)
                            else:
                                print(f"❌ 编号 {part} 超出范围")
                                break
                        else:
                            print(f"❌ 无效编号: {part}")
                            break
                    else:
                        # 所有编号都有效
                        if selected_indices:
                            selected_categories = [available_categories[i]['name'] for i in selected_indices]
                            print(f"✅ 已选择品类: {', '.join(selected_categories)}")
                            
                            # 预估数据量
                            estimated_data = len(selected_categories) * 300
                            print(f"📊 预估数据量: {estimated_data}-{estimated_data + len(selected_categories) * 50} 条")
                            
                            return selected_categories
                        else:
                            print("❌ 请至少选择一个品类")
                    
                except KeyboardInterrupt:
                    print("\n👋 用户取消操作")
                    return []
                except Exception as e:
                    print(f"❌ 选择错误: {e}")
            
        except Exception as e:
            print(f"❌ 品类发现失败: {e}")
            return []
    
    def confirm_crawl_plan(self, city_name: str, categories: List[str]) -> bool:
        """确认爬取计划"""
        print(f"\n📋 爬取计划确认:")
        print(f"  🏙️  目标城市: {city_name}")
        print(f"  🎯 选择品类: {', '.join(categories)}")
        print(f"  📊 预估数据: {len(categories) * 300}-{len(categories) * 350} 条")
        print(f"  ⏱️  预估时间: {len(categories) * 15}-{len(categories) * 20} 分钟")
        
        # 显示当前系统状态
        scheduler_status = self.crawler.scheduler.get_scheduler_status()
        print(f"  🌐 当前网络: {scheduler_status['current_network']}")
        print(f"  ⏰ 当前时段: {scheduler_status['current_time_slot']}")
        
        while True:
            try:
                confirm = input("\n确认开始爬取? (y/n): ").strip().lower()
                
                if confirm in ['y', 'yes', '是', '确认']:
                    return True
                elif confirm in ['n', 'no', '否', '取消']:
                    return False
                else:
                    print("❌ 请输入 y(是) 或 n(否)")
                    
            except KeyboardInterrupt:
                print("\n👋 用户取消操作")
                return False
    
    def execute_crawl(self, city_name: str, categories: List[str]) -> bool:
        """执行爬取"""
        print(f"\n🚀 开始执行爬取任务...")
        print("=" * 60)
        
        try:
            # 开始智能爬取
            success = self.crawler.start_smart_crawl_with_discovery(
                city_name=city_name,
                selected_categories=categories,
                target_data_count=len(categories) * 350
            )
            
            print("=" * 60)
            
            if success:
                print("🎉 爬取任务成功完成！")
                
                # 显示最终统计
                if self.crawler.monitor:
                    performance = self.crawler.monitor.get_performance_summary()
                    print(f"📊 本次爬取统计:")
                    print(f"  数据量: {performance['daily_total']} 条")
                    print(f"  成功率: {performance['current_success_rate']:.1%}")
                    print(f"  会话数: {performance['sessions_count']}")
                
                return True
            else:
                print("❌ 爬取任务失败")
                print("💡 建议检查账号状态和网络连接")
                return False
                
        except Exception as e:
            print(f"❌ 爬取执行异常: {e}")
            return False
    
    def run(self):
        """运行主流程"""
        try:
            # 显示欢迎界面
            self.print_welcome_banner()
            
            # 初始化系统
            if not self.initialize_system():
                return 1
            
            # 显示系统状态
            if not self.show_system_status():
                print("⚠️ 系统状态异常，但仍可尝试继续")
            
            # 城市选择
            city_name = self.select_city()
            if not city_name:
                print("👋 未选择城市，退出程序")
                return 0
            
            # 品类发现和选择
            categories = self.discover_and_select_categories(city_name)
            if not categories:
                print("👋 未选择品类，退出程序")
                return 0
            
            # 确认爬取计划
            if not self.confirm_crawl_plan(city_name, categories):
                print("👋 用户取消爬取，退出程序")
                return 0
            
            # 执行爬取
            success = self.execute_crawl(city_name, categories)
            
            if success:
                print("\n🎊 任务完成！感谢使用智能爬取系统")
                return 0
            else:
                print("\n😞 任务失败，请检查日志了解详情")
                return 1
                
        except KeyboardInterrupt:
            print("\n👋 用户中断程序，再见！")
            return 0
        except Exception as e:
            print(f"\n❌ 程序异常: {e}")
            logger.error(f"程序异常: {e}")
            return 1

def main():
    """主函数"""
    launcher = SimpleCrawlLauncher()
    return launcher.run()

if __name__ == "__main__":
    sys.exit(main())
